package com.tencent.cloud.uikit.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;

import com.tencent.cloud.uikit.R;

import java.util.Arrays;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

/**
 * 权限工具类
 *
 * @author showxiao
 * @date 2018/10/25
 */
public final class PermissionUtils {

    private static final int PERMISSION_REQUEST_CODE = 1;

    private static final String[] PERMISSION_CAMERA = new String[]{Manifest.permission.CAMERA};

    public static boolean hasCameraPermissions(Context context) {
        return EasyPermissions.hasPermissions(context, PERMISSION_CAMERA);
    }

    public static void requestCameraPermissions(Fragment fragment) {
        if (EasyPermissions.somePermissionPermanentlyDenied(
                fragment, Arrays.asList(PERMISSION_CAMERA))) {
            new AppSettingsDialog.Builder(fragment)
                    .setTitle(R.string.permission_title)
                    .setRationale(R.string.permission_rationale_camera_setting)
                    .setPositiveButton(R.string.setup)
                    .build().show();
        } else {
            PermissionRequest request = new PermissionRequest
                    .Builder(fragment, PERMISSION_REQUEST_CODE, PERMISSION_CAMERA)
                    .setRationale(R.string.permission_rationale_camera)
                    .setPositiveButtonText(R.string.setup)
                    .build();
            EasyPermissions.requestPermissions(request);
        }
    }

    public static void requestCameraPermissions(Activity activity) {
        if (EasyPermissions.somePermissionPermanentlyDenied(
                activity, Arrays.asList(PERMISSION_CAMERA))) {
            new AppSettingsDialog.Builder(activity)
                    .setTitle(R.string.permission_title)
                    .setRationale(R.string.permission_rationale_camera_setting)
                    .setPositiveButton(R.string.setup)
                    .build().show();
        } else {
            PermissionRequest request = new PermissionRequest
                    .Builder(activity, PERMISSION_REQUEST_CODE, PERMISSION_CAMERA)
                    .setRationale(R.string.permission_rationale_camera)
                    .setPositiveButtonText(R.string.setup)
                    .build();
            EasyPermissions.requestPermissions(request);
        }
    }

    public static boolean isSettingsPermissionRequest(int requestCode) {
        return AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE == requestCode;
    }
}
